import request from '@/utils/axios'
import {message} from "ant-design-vue";
import {getObjectValue, setObjectValue, trans} from "@/utils/index";
import {forEach ,cloneDeep} from 'lodash'
import {state} from '@/store/index'
import {isReactive} from "vue";
export default function (config,gridBatch = false,selected = [],instance=null,updateObject=null){
    return new Promise((resolve, reject) => {
        const options = cloneDeep(config)

        let modelValue = state.modelValue
        if(instance && instance.scopeProp && instance.scopeProp.row){
            modelValue = instance.scopeProp.row
        }
        if(updateObject){
            modelValue = updateObject
        }
        forEach(options.data,function (value,key){
            if(key.indexOf(':') === 0){

                options.data[key.substr(1)] = getObjectValue(modelValue,value)
                delete options.data[key]
            }
        })
        if(gridBatch){
            if(selected.length == 0){
                return message.warn(trans('Grid.selectedAction'))
            }
            if(Array.isArray(options.data)){
                options.data = {}
            }
            options.data.selected = selected
        }
        if(options.data && options.data.ex_admin_ajax_action && instance){
            Object.assign(options.data,instance.grid.exposed.requestDataParams())
        }
        if(options.method.toUpperCase() === 'GET'){
            options.params = options.data
        }
        request(options).then(res => {
            if(res.bindData){
                forEach(res.bindData,function (value,key){
                    if(isReactive(getObjectValue(modelValue,key))){
                        setObjectValue(modelValue,key,[])
                        setTimeout(()=>{
                            setObjectValue(modelValue,key,value)
                        })
                    }else{
                        setObjectValue(modelValue,key,value)
                    }

                })
            }
            resolve(res)
        }).catch((res)=>{
            reject(res)
        })
    })
}
